<template>
  <div>
    <a-modal v-model="visible" title="还货" :width="900" centered okText="确认还货" @ok="handleSubmit" destroyOnClose class="return-modal" :ok-button-props="{ props: { disabled: okDisabled } }">
      <p class="tip">温馨提示：请记得联系客户寄回商品！</p>
      <div class="title">待还商品：{{ data.length }}件（含补单商品，不含已购买、删款、已入库商品）</div>
      <GoodsTable :tableData="data" :tableType="'return'" @getData="getData"></GoodsTable>
      <a-checkbox v-model="virtual" style="margin-top: 32px">虚拟还货</a-checkbox>
      <section style="margin-top: 12px" v-show="!virtual">
        <a-tabs default-active-key="1" @change="handleChange">
          <a-tab-pane key="1" tab="预约快递">
            <AppointmentExpress :unionId="unionId" :defLogistic="defLogistic" @changePickTime="changePickTime" @changeAddress="changeAddress"></AppointmentExpress>
          </a-tab-pane>
          <a-tab-pane key="2" tab="客户寄回" force-render>
            <a-form>
              <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="退款金额" required>
                <a-input-number v-model="mdl.refundAmount" :min="0" :step="0.01" class="discount-input" placeholder="请输入" :autoFocus="true" :style="{ width: '50%' }" />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="是否退款单" required>
                <a-radio-group name="radioGroup" v-model="mdl.isRefund">
                  <a-radio :value="0">否</a-radio>
                  <a-radio :value="1">是</a-radio>
                </a-radio-group>
              </a-form-item> -->

              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="物流单号">
                <a-input v-model="mdl.logSn" placeholder="请输入" allowClear />
              </a-form-item>
              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="物流公司">
                <a-select v-model="mdl.logName" placeholder="请选择">
                  <a-select-option :value="item.id" v-for="(item, index) in companyList" :key="index">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">
                <a-textarea v-model="mdl.memo" placeholder="" :auto-size="{ minRows: 3, maxRows: 5 }" :maxLength="200" />
              </a-form-item>
            </a-form>
          </a-tab-pane>
        </a-tabs>
        <!-- <div class="title">预约快递</div> -->
      </section>
    </a-modal>
    <a-modal :visible="goodVisible" @ok="goodOk" @cancel="goodCancel" :maskClosable="false" centered :closable="false" :width="400">
      <p style="margin-top: 40px; font-size: 16px">存在未签收商品,是否还货？</p>
    </a-modal>
  </div>
</template>
<script>
import GoodsTable from './goodsTable'
import AppointmentExpress from './appointmentExpress'
import { getReturnBoxDetails, returnProduct, createReturnOrder } from '@/api/box/order'
import { selectLogistics } from '@/api/box/workbench'
import { getLogisticsCompany } from '@/views/box/util/global'
import globalData from '@/views/box/util/global'
export default {
  components: {
    GoodsTable,
    AppointmentExpress
  },
  data() {
    return {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 }
      },
      visible: false,
      unionId: 'oZpUxs18tKD3pGg2fXyeehBKrrEI',
      defLogistic: {},
      logisticsId: '',
      boxId: '',
      data: [],
      pickTime: [],
      newAddress: {},
      activeTab: 1,
      companyList: [],
      mdl: {
        isRefund: 0
      },
      okDisabled: false,
      goodVisible: false,
      selectedData: [], // 选中的数据
      virtual: false
    }
  },
  methods: {
    async show(id, unionid, defLogisticId) {
      if (globalData.logisticsCompany && globalData.logisticsCompany.length > 0) {
        this.companyList = globalData.logisticsCompany
      } else {
        this.companyList = await getLogisticsCompany()
      }
      this.mdl = { isRefund: 0 }
      this.virtual = false
      this.visible = true
      this.boxId = id
      this.unionId = unionid
      this.logisticsId = defLogisticId
      // this.newAddress = {
      //   id: defLogisticId
      // }

      this.getOrderLogistic()
      this.getReturnGoods()
    },
    getOrderLogistic() {
      selectLogistics(this.unionId)
        .then(res => {
          if (res.code === 0) {
            if (res.data && res.data.length > 0) {
              const result = res.data.filter(e => e.id == this.logisticsId)
              if (result.length > 0) {
                this.defLogistic = result[0]
              } else {
                let def = res.data.filter(e => e.logDefault == 1)
                if (def.length > 0) {
                  this.defLogistic = def[0]
                } else {
                  this.defLogistic = res.data[0]
                }
              }
            } else {
              this.defLogistic = {}
            }
            this.newAddress = this.defLogistic
            console.log(this.defLogistic)
          } else {
            this.$message.error(res.data)
          }
        })
        .catch(err => {
          console.log('查看顾客地址列表:' + err)
        })
    },
    getReturnGoods() {
      let params = {
        requestData: {
          boxId: this.boxId
        }
      }
      getReturnBoxDetails(params).then(res => {
        if (res.code == 0) {
          this.data = res.data
          this.boxDetailsId = this.data.map(item => {
            return item.id
          })
        }
      })
    },
    handleChange(key) {
      console.log(key)
      this.activeTab = key
    },
    // 还货ID集合
    getData(data) {
      this.selectedData = data
      this.boxDetailsId = data.map(item => {
        return item.id
      })
    },
    // 选择时间
    onChange(value) {
      console.log(value)
      this.pickTime = value
    },
    chooseAddress() {
      this.$refs.address.show()
    },
    // 选择时间
    changePickTime(value) {
      this.pickTime = value
      console.log(this.pickTime)
    },
    // 变更地址
    changeAddress(record) {
      this.newAddress = record
    },
    // 还货
    stillGoods() {
      this.okDisabled = true
      let params = {}
      if (this.activeTab == 1 && !this.virtual) {
        // 预约快递
        // console.log(this.newAddress)
        if (!this.virtual) {
          if (!this.newAddress.id) {
            this.$message.warning('请选择地址！')
            this.okDisabled = false
            return
          }
          if (this.pickTime.length == 0) {
            this.$message.warning('请选择时间！')
            this.okDisabled = false
            return
          }
        }

        params = {
          requestData: {
            boxId: this.boxId,
            ifVirBack: this.virtual ? 1 : 0,
            boxDetailsId: this.boxDetailsId,
            getDate: this.pickTime[0] + ' ' + this.pickTime[1],
            customerLogisticsId: this.newAddress.id
          }
        }

        returnProduct(params).then(res => {
          if (res.code == 0) {
            this.$message.success('预约快递成功！')
            this.visible = false
            this.$emit('updateTable')
            this.$emit('refresh')
          } else {
            this.$message.warning(res.msg)
          }
          this.okDisabled = false
        })
      }
      if (this.activeTab == 2 || this.virtual) {
        // 客户寄回
        // if (!this.mdl.refundAmount) {
        //   this.$message.warning('请输入退款金额！')
        //   this.okDisabled = false
        // } else
        if (!this.virtual) {
          if (!(this.mdl.logSn && this.mdl.logName)) {
            this.$message.warning('请关联物流单!')
            this.okDisabled = false
            return
          }
        }

        params = {
          requestData: {
            boxId: this.boxId,
            boxDetailsId: this.boxDetailsId,
            ifVirBack: this.virtual ? 1 : 0
          }
        }
        if (!this.virtual) {
          Object.assign(params.requestData, this.mdl)
        }

        createReturnOrder(params).then(res => {
          if (res.code == 0) {
            this.$message.success('还货成功！')
            this.visible = false
            this.$emit('updateTable')
            this.$emit('refresh')
          } else {
            this.$message.warning(res.msg)
          }
          this.okDisabled = false
        })
      }
    },
    // 取消
    goodCancel() {
      this.goodVisible = false
    },
    // 确认
    goodOk() {
      this.stillGoods()
      this.goodVisible = false
    },
    handleSubmit() {
      let statusType = this.selectedData.some(item => {
        return item.status === 0 || item.status === 8
      })

      if (statusType) {
        this.goodVisible = true
      } else {
        this.stillGoods()
      }
    }
  }
}
</script>
<style src="../less/modal.less" lang="less" scoped></style>

